﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Controls
{
    public partial class OrderDetails : ControlBaseClass
    {

        public string OrderID;
        public String moneyFormat = "C";
        public bool sendCustomerReceiptEmail = false;
        public bool useGoogleAnalyticsTransactionTracking = false;
        public OrderProperties orderDetailsProperties;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            if (String.IsNullOrEmpty(OrderID)) return;


            WebsiteAddressDisplay.NicknameVisible = false;
            WebsiteAddressDisplay.FaxVisible = false;

            WebsiteAddressDisplay.Address.AddressCompanyName = ParentPage.Website.BusinessName;
            WebsiteAddressDisplay.Address.AddressLine1 = ParentPage.Website.BusinessAddress1;
            WebsiteAddressDisplay.Address.AddressLine2 = ParentPage.Website.BusinessAddress2;
            WebsiteAddressDisplay.Address.AddressCity = ParentPage.Website.BusinessCity;
            WebsiteAddressDisplay.Address.AddressStateProvIDPostalAbrev = ParentPage.Website.BusinessStateProvIDPostalAbrev;
            WebsiteAddressDisplay.Address.AddressPostalCode = ParentPage.Website.BusinessPostalCode;
            WebsiteAddressDisplay.Address.AddressPhone = ParentPage.Website.BusinessPhone;
            WebsiteAddressDisplay.Address.AddressCountryIDPostalAbrev = ParentPage.Website.BusinesssCountryIDPostalAbrev;

            EmailLiteral.Text = ParentPage.Website.OrderManagementEmail;


            DataSet orderDetailsDataset = null;
            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
            args.Add("CustomerCartSessionID", ParentPage.CustomerCartSessionID);
            args.Add("OrderID", OrderID);
            APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "OrderDetail", args, false, false);
            if (env.response != null)
            {
                string response = (string)env.response;
                orderDetailsDataset = new DataSet();
                orderDetailsDataset.ReadXml(new StringReader((string)env.response));
            }

            if (orderDetailsDataset.Tables.Count != 3)
            {
                //Response.Write("Empty");
                return;
            }

            DataTable orderDetailTable = orderDetailsDataset.Tables[0];
            DataTable paymentsTable = orderDetailsDataset.Tables[1];
            DataTable orderLinesTable = orderDetailsDataset.Tables[2];

            if (orderDetailsDataset == null || orderDetailTable.Rows.Count == 0 || orderLinesTable == null || orderLinesTable.Rows.Count == 0)
            {
                //Response.Write("Empty");
                return;
            }

            if (paymentsTable != null && paymentsTable.Rows.Count > 0)
            {
                PaymentListRepeater.DataSource = paymentsTable;
                PaymentListRepeater.DataBind();
            }

            orderDetailsProperties = OrderProperties.Create(orderDetailsDataset);

            SubTotalLabel.Text = orderDetailsProperties.SubTotal.Value.ToString(moneyFormat);
            ShippingLabel.Text = orderDetailsProperties.ShippingChargeAmount.Value.ToString(moneyFormat);
            CountrySurchargeLabel.Text = orderDetailsProperties.CountrySurchargeAmount.Value.ToString(moneyFormat);
            SalesTaxLabel.Text = orderDetailsProperties.TaxTotal.Value.ToString(moneyFormat);
            TotalLabel.Text = orderDetailsProperties.GrandTotal.Value.ToString(moneyFormat);

            if (sendCustomerReceiptEmail)
            {
                StringWriter SW = new StringWriter();
                Server.Execute("/OrderDetailsReceiptEmail.aspx?OrderID=" + OrderID, SW);

                args = new Dictionary<string, object>();
                args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
                args.Add("CustomerCartSessionID", ParentPage.CustomerCartSessionID);
                args.Add("EmailTo", orderDetailsProperties.CustomerUsernameEmail);
                args.Add("EmailFrom", ParentPage.Website.OrderManagementEmail);
                args.Add("Subject", "Your order");
                args.Add("EmailBody", SW.ToString());
                args.Add("IsHTML", true);
                env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CustomerSendEmail", args, false, false);

            }

            if (ParentPage.Website.IsDebugMode == true)
            {

                moneyFormat = "C4";
                DebugInfoLiteral.Visible = true;
                DebugInfoLiteral.Text = "";
                DebugInfoLiteral.Text += "<br />WeightTotal: " + orderDetailsProperties.WeightTotal.Value.ToString();
                DebugInfoLiteral.Text += "<br />SubTotal: " + orderDetailsProperties.SubTotal.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /><br /> ShipMethDisplayName: " + orderDetailsProperties.ShipMethDisplayName.ToString();
                DebugInfoLiteral.Text += "<br /> SovShipMethodIDCode: " + orderDetailsProperties.SovShipMethodIDCode.ToString();
                DebugInfoLiteral.Text += "<br />ShippingCharge: " + orderDetailsProperties.ShippingChargeAmount.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /><br /> TaxSUBTotal: " + orderDetailsProperties.TaxSubTotal.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> ShippingTaxAmount: " + orderDetailsProperties.ShippingTaxAmount.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> ShippingTaxRateHistory: " + orderDetailsProperties.ShippingTaxRateHistory.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> SalesTaxTotal: " + orderDetailsProperties.TaxTotal.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> CountrySurcharge: " + orderDetailsProperties.CountrySurchargeAmount.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> CountrySurchargeRateHistory: " + orderDetailsProperties.CountrySurchargeRateHistory.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /><br /> GrandTotal: " + orderDetailsProperties.GrandTotal.Value.ToString(moneyFormat);
                DebugInfoLiteral.Text += "<br /> CartCreateDate: " + orderDetailsProperties.OrderCreateDate.Value.ToString();
                DebugInfoLiteral.Text += "<br /> CustomerCartSessionID: " + ParentPage.Customer.CustomerCartSessionID.ToString();
                DebugInfoLiteral.Text += "<br /> OrderProp IsCreditApproved: " + orderDetailsProperties.IsCreditApproved.ToString();
                DebugInfoLiteral.Text += "<br /> Inactive: " + ParentPage.Customer.IsInactive.ToString();
                DebugInfoLiteral.Text += "<br /> OrderProp Tax Exempt: " + orderDetailsProperties.IsStateProvJurisTaxExempt.ToString();
                DebugInfoLiteral.Text += "<br /> UserName/Email: " + orderDetailsProperties.CustomerUsernameEmail.ToString();

            }

            CartLineRepeater.DataSource = orderLinesTable;
            CartLineRepeater.DataBind();

            //Populate "Shipping Address" section.
            ShippingAddressDisplay.NicknameVisible = false;
            ShippingAddressDisplay.FaxVisible = false;

            ShippingAddressDisplay.Address.AddressCompanyName = orderDetailsProperties.ShipCompanyName;
            ShippingAddressDisplay.Address.AddressLine1 = orderDetailsProperties.ShipAddress1;
            ShippingAddressDisplay.Address.AddressLine2 = orderDetailsProperties.ShipAddress2;
            ShippingAddressDisplay.Address.AddressCity = orderDetailsProperties.ShipCity;
            ShippingAddressDisplay.Address.AddressStateProvIDPostalAbrev = orderDetailsProperties.ShipStateProv;
            ShippingAddressDisplay.Address.AddressPostalCode = orderDetailsProperties.ShipPostalCode;
            ShippingAddressDisplay.Address.AddressPhone = orderDetailsProperties.ShipPhone;
            ShippingAddressDisplay.Address.AddressCountryIDPostalAbrev = orderDetailsProperties.ShipCountry;


            //Populate "Ship Method" section.
            //------------------------------------------------------
            ShipMethodLiteral.Text = orderDetailsProperties.ShipMethDisplayName;
            ShippingChargeAmountLiteral.Text = orderDetailsProperties.ShippingChargeAmount.Value.ToString("C");
        
            if (!String.IsNullOrEmpty(ParentPage.Website.GoogleAnalyticsAccountID) && useGoogleAnalyticsTransactionTracking)
            {
                string googleCode = MiscUtils.ReadFile(Server.MapPath("~/Misc/GoogleAnalyticsAddTransactionJS.txt"));
                googleCode = googleCode.Replace("%OrderID%", orderDetailsProperties.OrderDisplayID.ToString());
                googleCode = googleCode.Replace("%GrandTotal%", orderDetailsProperties.GrandTotal.Value.ToString());
                googleCode = googleCode.Replace("%TaxTotal%", orderDetailsProperties.TaxTotal.Value.ToString());
                googleCode = googleCode.Replace("%ShippingTotal%", orderDetailsProperties.ShippingChargeAmount.Value.ToString());
                googleCode = googleCode.Replace("%City%", orderDetailsProperties.BillCity);
                googleCode = googleCode.Replace("%State%", orderDetailsProperties.BillStateProv);
                googleCode = googleCode.Replace("%Country%", orderDetailsProperties.BillCountry);
                GoogleAnalyticsTransactionTrackingLiteral.Text = googleCode;
            }
        }

        protected void CartLineRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            DataRow row = drv.Row;

            HtmlTableRow CartLineTR = (HtmlTableRow)(e.Item.FindControl("CartLineTR"));
            Label CartLineNameLabel = (Label)(e.Item.FindControl("CartLineNameLabel"));
            Label CartLineTotalLabel = (Label)(e.Item.FindControl("CartLineTotalLabel"));
            Label CartLinePriceLabel = (Label)(e.Item.FindControl("CartLinePriceLabel"));
            Label CartLineQuantityLabel = (Label)(e.Item.FindControl("CartLineQuantityLabel"));
            Label CartLineRetailerDiscountLabel = (Label)(e.Item.FindControl("CartLineRetailerDiscountLabel"));
            Label CartLineManufacturerDiscountLabel = (Label)(e.Item.FindControl("CartLineManufacturerDiscountLabel"));
            Label CartLineSurchargeLabel = (Label)(e.Item.FindControl("CartLineSurchargeLabel"));
            Literal PropertiesLiteral = (Literal)(e.Item.FindControl("PropertiesLiteral"));
            HyperLink DownloadHyperLink = (HyperLink)(e.Item.FindControl("DownloadHyperLink"));

            decimal PropertySurchargeTotal = DataUtils.GetDecimal(row, "PropertySurchargeTotal");

            if (PropertySurchargeTotal > 0)
            {

                XmlDocument xd = new XmlDocument();
                xd.LoadXml(DataUtils.GetStr(row, "PropertyXML"));

                XmlNodeList children = xd.FirstChild.SelectNodes("SKUProperty");

                PropertiesLiteral.Text = "<div class='properties'>";
                foreach (XmlNode childNode in children)
                {
                    String PropertyName = childNode.SelectSingleNode("PropertyName").InnerText;
                    String PropertyValue = childNode.SelectSingleNode("PropertyValue").InnerText;
                    Double Surcharge = Convert.ToDouble(childNode.SelectSingleNode("Surcharge").InnerText);
                    PropertiesLiteral.Text += "<div class='property'><span class='name'>" + PropertyName + "</span><span class='name'>(" + PropertyValue + ")</span>&nbsp;<span class='price'>+" + Surcharge.ToString(moneyFormat) + "</span></div>";
                }
                PropertiesLiteral.Text += "</div>";
                CartLineSurchargeLabel.Visible = true;
                CartLineSurchargeLabel.Text = "Surcharge +" + PropertySurchargeTotal.ToString(moneyFormat);
            }

            CartLineManufacturerDiscountLabel.Text = "-" + DataUtils.GetDecimal(row, "LineMfgDiscountAmount").ToString(moneyFormat);
            CartLineRetailerDiscountLabel.Text = "-" + DataUtils.GetDecimal(row, "LineRetailerDiscountAmount").ToString(moneyFormat);
            CartLineNameLabel.Text = DataUtils.GetStr(row, "ItemName")
                    + " - " + DataUtils.GetStr(row, "SKUName")
                   + " (" + DataUtils.GetStr(row, "SKU") + ")";

            if (orderDetailsProperties.AmountToPay == 0)
            {
                string downloadFile = DataUtils.GetStr(row, "SKUFile");
                if (!String.IsNullOrEmpty(downloadFile))
                {

                    if (DateTime.UtcNow.Subtract(orderDetailsProperties.OrderCreateDate.Value).Days > ParentPage.Website.ProductFileExpireDays)
                        DownloadHyperLink.Text = "Expired";

                    DownloadHyperLink.Visible = true;
                    DownloadHyperLink.NavigateUrl = "/Misc/ProductFileDownload.aspx?File=" + downloadFile + "&OrderID=" + OrderID;
                }
            }

            CartLineTotalLabel.Text = DataUtils.GetDecimal(row, "LineTotal").ToString(moneyFormat);
            CartLinePriceLabel.Text = DataUtils.GetDecimal(row, "UnitPrice").ToString(moneyFormat);
            CartLineQuantityLabel.Text = DataUtils.GetInt(row, "Quantity", 0).ToString();
            CartLineSurchargeLabel.Text = DataUtils.GetDecimal(row, "PropertySurchargeTotal", 0).ToString(moneyFormat);

            if (ParentPage.Website.IsDebugMode == true)
            {

                //debug info
                Literal LineDebugInfoLiteral = (Literal)(e.Item.FindControl("LineDebugInfoLiteral"));

                moneyFormat = "C4";

                LineDebugInfoLiteral.Visible = true;
                LineDebugInfoLiteral.Text = "";
                LineDebugInfoLiteral.Text += "<br />LineTaxableAmount: " + DataUtils.GetDecimal(row, "LineTaxableAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineStateProvJurisTaxAmount: " + DataUtils.GetDecimal(row, "StateProvJurisTaxAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />StateProvJurisTaxRateHistory: " + DataUtils.GetDecimal(row, "StateProvJurisTaxRateHistory").ToString();
                LineDebugInfoLiteral.Text += "<br />SKUWeight " + DataUtils.GetDecimal(row, "Weight").ToString();
                LineDebugInfoLiteral.Text += "<br />LineWeightTotal: " + DataUtils.GetDecimal(row, "LineWeightTotal", 0).ToString();
                LineDebugInfoLiteral.Text += "<br />LineDiscountRateHistory: " + DataUtils.GetDecimal(row, "LineDiscountRateHistory").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineManufacturerDiscount: " + DataUtils.GetDecimal(row, "LineMfgDiscountAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineRetailerDiscount: " + DataUtils.GetDecimal(row, "LineRetailerDiscountAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineSurcharge: " + DataUtils.GetDecimal(row, "PropertySurchargeAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LinePropertyXML: " + Server.HtmlEncode(DataUtils.GetStr(row, "PropertyXML"));
                LineDebugInfoLiteral.Text += "<hr />";


            }


        }

        protected void PaymentListRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            DataRow row = drv.Row;

            Label PayMethDisplayNameLabel = (Label)(e.Item.FindControl("PayMethDisplayNameLabel"));
            Label PaymentCreateDateLabel = (Label)(e.Item.FindControl("PaymentCreateDateLabel"));
            Label PaymentAmountAcceptedLabel = (Label)(e.Item.FindControl("PaymentAmountAcceptedLabel"));

            PayMethDisplayNameLabel.Text = DataUtils.GetStr(row, "PayMethDisplayName");
            PaymentCreateDateLabel.Text = DataUtils.GetStr(row, "PaymentCreate");
            PaymentAmountAcceptedLabel.Text = DataUtils.GetDecimal(row, "PaymentAmountAccepted").ToString(moneyFormat);
        }

    }
}